package com.lw.leetcode.other.c;

/**
 * Created with IntelliJ IDEA.
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/13 11:12
 */
public class CountDigitOne {


    public static void main(String[] args) {
        CountDigitOne test = new CountDigitOne();
        // 27819
        int value = 1000000000;

        // 27819
//        int value = 42586;

        // 156
//        int value = 256;

        // 140
//        int value = 200;

        // 16
//        int value = 56;

        int aa = test.countDigitOne(value);
        System.out.println(aa);
    }

    public int countDigitOne(int n) {
        int sum = 0;
        if (n == 1000000000) {
            n--;
            sum++;
        }
        int[] arr = {0, 1, 20, 300, 4000, 50000, 600000, 7000000, 80000000};
        int[] nums = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
        int length = String.valueOf(n).length();
        for (int i = length - 1; i > 0; i--) {
            int m = n / nums[i];
            n = n % nums[i];
            sum = sum + m * arr[i];
            if (m > 1) {
                sum = sum + nums[i];
            } else if (m == 1) {
                sum = sum + n + 1;
            }
        }
        if (n >= 1) {
            sum++;
        }
        return sum;
    }

}
